package com.scuec.tourismwebsite.controller;

import com.github.pagehelper.PageInfo;
import com.scuec.tourismwebsite.entity.User;
import com.scuec.tourismwebsite.service.UserService;
import com.scuec.tourismwebsite.util.FileUtil;
import com.scuec.tourismwebsite.vo.UserPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("tour/v1")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("user")
    public List<User> findUserAll() {
        return userService.findUserAll();
    };


    @PostMapping("/user/check-password")
    public ResponseEntity<String> checkPassword(@RequestBody Map<String, String> data) {
        Integer user_id = Integer.parseInt(data.get("user_id"));
        String originalPassword = data.get("originalPassword");

        boolean result = userService.checkUserPassword(user_id, originalPassword);
        if (result) {
            return ResponseEntity.ok("原始密码正确");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("原始密码错误");
        }
    }
    @PutMapping("/user/update-password")
    public ResponseEntity<String> updatePassword(@RequestBody Map<String, String> data) {
        Integer user_id = Integer.parseInt(data.get("user_id"));
        String originalPassword = data.get("originalPassword"); // 添加原始密码参数
        String newPassword = data.get("newPassword");

        boolean result = userService.checkUserPassword(user_id, originalPassword);
        if (!result) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("原始密码错误");
        }

        boolean updateResult = userService.updatePassword(user_id, newPassword);
        if (updateResult) {
            return ResponseEntity.ok("密码更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("密码更新失败");
        }
    }
    @PutMapping("/user/update")
    public ResponseEntity<String> updateUser(@RequestBody User user) {
        System.out.println("Received user data: " + user);
        try {
            int result = userService.updateUser(user);
            if (result > 0) {
                return ResponseEntity.ok("用户信息更新成功");
            } else {
                return ResponseEntity.badRequest().body("用户信息更新失败");
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }

    @PostMapping("/user/upload")    // 图片上传
    public String getPicFileName(@RequestParam("file") MultipartFile file) {
        String oldFileName = file.getOriginalFilename();
        String typeName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String filePath = FileUtil.getUploadFilePath(); // 图片保存路径
        String newFileName = System.currentTimeMillis() + typeName;
        String avatar = newFileName;

        // 确保图片路径正确，存储到指定路径
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return avatar;  // 返回图片的完整 URL
    }

    @GetMapping("/user/posts/{user_id}")
    public ResponseEntity<List<UserPost>> getUserPosts(@PathVariable("user_id") int user_id) {
        List<UserPost> userPosts = userService.getUserPosts(user_id);
        if (userPosts != null && !userPosts.isEmpty()) {
            return ResponseEntity.ok(userPosts);
        } else {
            return ResponseEntity.notFound().build();
        }
    }




    @GetMapping("/user/phone")
    public ResponseEntity<String> getUserPhoneNumber(@RequestParam("phone_number") String phone_number) {
        String phoneNumber = userService.getPhoneNumberByUserId(phone_number);
        if (phoneNumber != null) {
            System.out.println("用户ID对应的电话号码: " + phoneNumber); // 添加日志
            return ResponseEntity.ok(phoneNumber);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/profile")
    public User findUserByPhone(@RequestParam("phone_number") String phone_number) {
        return userService.findUserByPhone(phone_number);
    }

    @DeleteMapping("user/{id}")
    public int deleteUserById(@PathVariable("id") int user_id) {
        return userService.deleteUserById(user_id);
    }

    @GetMapping("userpages")
    public PageInfo<User> findUserPages(Integer pageNum, Integer pageSize) {
        return userService.findUserPages(pageNum, pageSize);
    }
    ;

    @GetMapping("user/{id}")
    public User getUserById(@PathVariable("id") int user_id){
        return userService.getUserById(user_id);
    };



    @GetMapping("userpage")
    public PageInfo<User> findUserPage(String nickname, Integer pageNum, Integer pageSize) {
        return userService.findUserPage(nickname, pageNum, pageSize);

    }

    ;

    @GetMapping("bozhupages")
    public PageInfo<User> bozhuPages(Integer pageNum, Integer pageSize) {
        return userService.findUserPages(pageNum, pageSize);
    }

    ;

    @GetMapping("bozhupage")
    public PageInfo<User> bozhuPage(String nickname, Integer pageNum, Integer pageSize) {
        return userService.findUserPage(nickname, pageNum, pageSize);
    }

    @PostMapping("user")
    public String addUser(@RequestBody User user) {
        try {
            Integer result =userService.addUser(user);
            if (result > 0) {
                return "注册成功";
            } else {
                return "注册失败";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }}


    @PostMapping("/login2")
    public ResponseEntity<String> loginWithPhone(@RequestBody User loginRequest, HttpServletRequest request) {
        String phone = loginRequest.getPhone_number();
        String password = loginRequest.getPassword();

        User user = userService.loginByPhone(phone, password);

        // 添加调试日志
        System.out.println("登录请求 - 手机号: " + phone + ", 密码: " + password);
        if (user != null) {
            System.out.println("数据库匹配到的用户: " + user);
            request.getSession().setAttribute("user_id", user.getUser_id());
            return ResponseEntity.ok("登录成功");
        } else {
            System.out.println("登录失败 - 用户不存在或密码错误");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("手机号或密码错误");
        }
    }

}

//1